<template>
  <t-drawer
    :visible="visible"
    :header="drawerTitle"
    size="50%"
    placement="right"
    @close="handleClose"
  >
    <!-- 抽屉内容区域 -->
    <div class="recommend-drawer-body">
      <t-form
        ref="recommendForm"
        :data="formData"
        :rules="formRules"
        label-align="right"
        label-width="120px"
        class="recommend-form"
      >
        <!-- 疾病分类 -->
        <t-form-item label="疾病分类" name="categoryId">
          <t-select
            v-model="formData.categoryId"
            placeholder="请选择疾病分类"
            :loading="diseaseCategoryLoading"
            clearable
            style="width: 100%"
          >
            <t-option
              v-for="category in diseaseCategoryList"
              :key="category.id"
              :value="category.id"
              :label="category.name"
            >
              {{ category.name }}
            </t-option>
          </t-select>
        </t-form-item>

        <!-- 名称 -->
        <t-form-item label="名称" name="name">
          <t-input v-model="formData.name" placeholder="请输入推荐知识名称" maxlength="100" />
        </t-form-item>

        <!-- 编码 -->
        <t-form-item label="编码" name="code">
          <t-input
            v-model="formData.code"
            placeholder="请输入编码"
            maxlength="50"
            :disabled="isEdit"
          />
        </t-form-item>

        <!-- 作者 -->
        <t-form-item label="作者" name="author">
          <t-input v-model="formData.author" placeholder="请输入作者姓名" maxlength="50" />
        </t-form-item>

        <!-- 封面图片上传 -->
        <t-form-item label="封面图片" name="banner">
          <div style="display: flex; flex-direction: column; width: 100%;">
						<!-- 文件上传 -->
						<t-upload
							:action="uploadAction"
							:accept="'image/*'"
							:size-limit="{ size: 5, unit: 'MB' }"
							:format-response="formatImageResponse"
							:on-success="handleImageSuccess"
							:on-fail="handleUploadFail"
							@waiting-upload-files-change="handleImageProgress"
							:draggable="true"
							:show-upload-list="false"
							:auto-upload="true"
							:disabled="imageUploading"
							theme="custom"
							tips="支持拖拽上传，单个文件不超过5MB，支持JPG、PNG格式"
							style="width: 100%; margin-bottom: 8px;"
						>
							<template #drag-content>
								<div v-loading="imageUploading" class="upload-drag-content">
									<template>
										<t-icon name="cloud-upload" size="36px" />
										<div class="upload-text">
											<p>点击上传图片或将图片拖拽到此区域</p>
											<p class="upload-tips">支持 JPG、PNG 格式，单个文件不超过5MB</p>
										</div>
									</template>
								</div>
							</template>
						</t-upload>

          <!-- 文件列表 -->
          <div v-if="formData.banner.length > 0">
            <div class="file-list-header">
              <span class="file-count">已上传图片：{{ formData.banner.length }} 个</span>
            </div>
            <div class="file-list-container">
              <div
                v-for="(url, index) in formData.banner"
                :key="index"
                class="file-item"
              >
                <div class="file-preview" @click="previewImage(url, index)">
                  <img :src="url" :alt="`图片${index + 1}`" class="preview-thumbnail" />
                </div>
                <div class="file-info">
                  <t-icon name="image" class="file-icon" />
                  <span class="file-name">{{ getFileName(url) }}</span>
                </div>
                <div class="file-actions">
                  <t-button
                    theme="primary"
                    variant="text"
                    size="small"
                    @click="previewImage(url, index)"
                    title="预览"
                  >
                    <t-icon name="play-circle" />
                  </t-button>
                  <t-button
                    theme="danger"
                    variant="text"
                    size="small"
                    @click="removeFile('banner', index)"
                    title="删除"
                  >
                    <t-icon name="delete" />
                  </t-button>
                </div>
              </div>
            </div>
          </div>
					</div>
        </t-form-item>

        <!-- 视频上传 -->
        <t-form-item label="视频内容" name="video">
          <div style="display: flex; flex-direction: column; width: 100%;">
						<!-- 文件上传 -->
						<t-upload
            :action="uploadAction"
            :accept="'video/*'"
            :size-limit="{ size: 100, unit: 'MB' }"
            :format-response="formatVideoResponse"
            :on-success="handleVideoSuccess"
            :on-fail="handleUploadFail"
            @waiting-upload-files-change="handleVideoProgress"
            :draggable="true"
            :show-upload-list="false"
            :auto-upload="true"
            :disabled="videoUploading"
            theme="custom"
            tips="支持拖拽上传，单个文件不超过100MB，支持MP4、AVI、MOV格式"
            style="width: 100%; margin-bottom: 8px;"
          >
            <template #drag-content>
              <div v-loading="videoUploading" class="upload-drag-content">
                <template>
                  <t-icon name="video" size="36px" />
                  <div class="upload-text">
                    <p>点击上传视频或将视频拖拽到此区域</p>
                    <p class="upload-tips">支持 MP4、AVI、MOV 格式，单个文件不超过100MB</p>
                  </div>
                </template>
              </div>
            </template>
          </t-upload>

          <!-- 文件列表 -->
          <div v-if="formData.video.length > 0">
            <div class="file-list-header">
              <span class="file-count">已上传视频：{{ formData.video.length }} 个</span>
            </div>
            <div class="file-list-container">
              <div
                v-for="(url, index) in formData.video"
                :key="index"
                class="file-item"
              >
                <div class="file-preview" @click="playVideo(url)">
                  <div class="video-thumbnail">
                    <t-icon name="video" size="24px" />
                    <span class="play-icon">▶</span>
                  </div>
                </div>
                <div class="file-info">
                  <t-icon name="video" class="file-icon" />
                  <span class="file-name">{{ getFileName(url) }}</span>
                </div>
                <div class="file-actions">
                  <t-button
                    theme="primary"
                    variant="text"
                    size="small"
                    @click="playVideo(url)"
                    title="播放"
                  >
                    <t-icon name="play-circle" />
                  </t-button>
                  <t-button
                    theme="danger"
                    variant="text"
                    size="small"
                    @click="removeFile('video', index)"
                    title="删除"
                  >
                    <t-icon name="delete" />
                  </t-button>
                </div>
              </div>
            </div>
          </div>
					</div>
        </t-form-item>

        <!-- 内容 -->
        <t-form-item label="内容" name="content">
          <div class="rich-editor-wrapper">
            <Toolbar
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 400px"
              v-model="formData.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </t-form-item>
      </t-form>
    </div>

    <!-- 底部按钮区域 -->
    <template #footer>
      <div class="drawer-footer">
        <t-button
          variant="outline"
          theme="default"
          @click="handleCancel"
        >
          取消
        </t-button>
        <t-button
          theme="primary"
          @click="handleConfirm"
        >
          确定
        </t-button>
      </div>
    </template>
  </t-drawer>
</template>

<script>
// 引入富文本编辑器
import Vue from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';

import { getDiseaseList } from '@/api/disease';
import { createCatalogContent, updateCatalogContent, getCatalogContentById } from '@/api/catalog';

export default {
  name: 'RecommendDrawer',
  components: { Editor, Toolbar },
  model: {
    prop: 'visible',
    event: 'update:visible',
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    editData: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ['update:visible', 'success'],
  data() {
    return {
      editor: null,
      diseaseCategoryLoading: false,
      diseaseCategoryList: [],
      imageUploading: false,
      videoUploading: false,
      formData: {
        id: null,
        categoryId: null,
        name: '',
        code: '',
        author: '',
        banner: [],
        video: [],
        content: '<p>请输入推荐知识内容...</p>',
      },
      formRules: {
        categoryId: [{ required: true, message: '请选择疾病分类', trigger: 'change' }],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 100, message: '名称不能超过100个字符', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9_-]+$/,
            message: '编码只能包含字母、数字、下划线和横线',
            trigger: 'blur',
          },
          { max: 50, message: '编码不能超过50个字符', trigger: 'blur' },
        ],
        author: [
          { required: true, message: '请输入作者姓名', trigger: 'blur' },
          { max: 50, message: '作者姓名不能超过50个字符', trigger: 'blur' },
        ],
        content: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'change',
            validator: (val) => {
              if (!val) return false;
              // 移除HTML标签后检查是否有实际内容
              const textContent = val.replace(/<[^>]*>/g, '').trim();
              return textContent.length > 0;
            },
          },
        ],
      },
      uploadAction: '/api/cms/tools/upload', // 上传接口地址，需要根据实际情况修改
      // 富文本编辑器配置
      toolbarConfig: {
        toolbarKeys: [
          'headerSelect',
          '|',
          'bold',
          'italic',
          'underline',
          'through',
          'code',
          'sup',
          'sub',
          'clearStyle',
          '|',
          'color',
          'bgColor',
          '|',
          'fontSize',
          'fontFamily',
          'lineHeight',
          '|',
          'bulletedList',
          'numberedList',
          '|',
          'justifyLeft',
          'justifyRight',
          'justifyCenter',
          'justifyJustify',
          '|',
          'insertTable',
          'codeBlock',
          'divider',
          '|',
          'undo',
          'redo',
        ],
      },
      editorConfig: {
        placeholder: '请输入推荐知识内容...',
        MENU_CONF: {
          // 禁用上传功能
          uploadImage: {
            server: '',
          },
          uploadVideo: {
            server: '',
          },
        },
      },
      mode: 'default', // or 'simple'
    };
  },
  computed: {
    isEdit() {
      return !!(this.editData && this.editData.id);
    },
    drawerTitle() {
      return this.isEdit ? '编辑推荐知识' : '新建推荐知识';
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadDiseaseCategoryList();
        this.initFormData();
      }
    },
    editData: {
      handler() {
        if (this.visible) {
          this.initFormData();
        }
      },
      deep: true,
    },
  },
  methods: {
    handleClose() {
      // 重置表单数据到初始状态
      this.formData = {
        id: null,
        categoryId: null,
        name: '',
        code: '',
        author: '',
        banner: [],
        video: [],
        content: '<p>请输入推荐知识内容...</p>',
      };

      // 重置loading状态
      this.imageUploading = false;
      this.videoUploading = false;

      // 重置表单验证状态
      if (this.$refs.recommendForm) {
        this.$refs.recommendForm.clearValidate();
      }

      this.$emit('update:visible', false);
    },

    handleCancel() {
      this.handleClose();
    },

    async handleConfirm() {
      try {
        // 验证表单
        const valid = await this.$refs.recommendForm.validate();

        if (valid !== true) {
          return;
        }

        const params = {
          ...this.formData,
          banner: this.formData.banner.join(','),
          video: this.formData.video.join(','),
          rawHtml: this.formData.content, // 将content作为rawHtml传递
					type: 'SCIENCE_KNOWLEDGE'
        };

        // 移除content字段，避免重复
        delete params.content;

        // 根据是否有id决定调用创建还是更新接口
        if (this.formData.id) {
          // 有id，调用更新接口
          await updateCatalogContent(this.formData.id, params);
          this.$message.success('更新成功');
        } else {
          // 无id，调用创建接口
          await createCatalogContent(params);
          this.$message.success('创建成功');
        }

        this.$emit('success', this.formData);
        this.handleClose();
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error(this.formData.id ? '更新失败，请重试' : '创建失败，请重试');
      }
    },

    // 初始化表单数据
    async initFormData() {
      if (this.isEdit && this.editData.id) {
        try {
          // 如果是编辑模式，从接口获取详细数据
          const res = await getCatalogContentById(this.editData.id);
          if (res?.data?.data) {
            const data = res.data.data;
            this.formData = {
              id: data.id,
              categoryId: data.categoryId,
              name: data.name || '',
              code: data.code || '',
              author: data.author || '',
              banner:
                data.banner && data.banner.trim()
                  ? data.banner.split(',').filter((url) => url.trim())
                  : [],
              video:
                data.video && data.video.trim()
                  ? data.video.split(',').filter((url) => url.trim())
                  : [],
              content: data.rawHtml || '<p>请输入推荐知识内容...</p>',
            };
          }
        } catch (error) {
          console.error('获取推荐知识详情失败:', error);
          this.$message.error('获取数据失败，请重试');
        }
      } else {
        // 新建模式，重置表单数据
        this.formData = {
          id: null,
          categoryId: null,
          name: '',
          code: '',
          author: '',
          banner: [],
          video: [],
          content: '<p>请输入推荐知识内容...</p>',
        };
      }
    },

    // 加载疾病分类列表
    async loadDiseaseCategoryList() {
      this.diseaseCategoryLoading = true;
      try {
        const res = await getDiseaseList();
        this.diseaseCategoryList = res?.data?.data || [];
      } catch (error) {
        console.error('加载疾病分类失败:', error);
        this.$message.error('加载疾病分类失败');
        this.diseaseCategoryList = [];
      } finally {
        this.diseaseCategoryLoading = false;
      }
    },

    // 图片上传进度回调
    handleImageProgress(percent, file) {
      console.log('图片上传进度:', percent, file);
      this.imageUploading = true;
    },

    // 视频上传进度回调
    handleVideoProgress(percent, file) {
      console.log('视频上传进度:', percent, file);
      this.videoUploading = true;
    },

    // 图片上传成功回调
    handleImageSuccess(response, file) {
      console.log('图片上传成功:', response, file);
      this.imageUploading = false;
      // 直接将链接追加到banner数组中
      const url = response.response?.url ?? '';
      if (url) {
        this.formData.banner = [...this.formData.banner, url];
        this.$message.success('图片上传成功');
      }
    },

    // 视频上传成功回调
    handleVideoSuccess(response, file) {
      console.log('视频上传成功:', response, file);
      this.videoUploading = false;
      // 直接将链接追加到video数组中
      const url = response.response?.url ?? '';
      if (url) {
        this.formData.video = [...this.formData.video, url];
        this.$message.success('视频上传成功');
      }
    },

    // 上传失败回调
    handleUploadFail(error) {
      console.error('上传失败:', error);
      this.imageUploading = false;
      this.videoUploading = false;
      this.$message.error('上传失败，请重试');
    },

    // 格式化图片上传响应
    formatImageResponse(response) {
      console.log('图片上传响应:', response);
      // 根据实际接口返回格式调整
      return {
        url: response.data ?? '',
        name: response.data ? response.data.split('/').pop() : '',
      };
    },

    // 格式化视频上传响应
    formatVideoResponse(response) {
      console.log('视频上传响应:', response);
      // 根据实际接口返回格式调整
      return {
        url: response.data ?? '',
        name: response.data ? response.data.split('/').pop() : '',
      };
    },

    // 删除图片
    async removeFile(type, index) {
      const { DialogPlugin } = await import('tdesign-vue');

      const confirmDialog = await new Promise((resolve) => {
        const instance = DialogPlugin.confirm({
          header: '确认删除',
          body: '确定要删除这个文件吗？',
          confirmBtn: {
            content: '确定删除',
            theme: 'danger',
            loading: false
          },
          cancelBtn: '取消',
          onConfirm: () => {
            resolve(instance);
          },
          onCancel: () => {
            resolve(null);
          },
        });
      });

      if (confirmDialog) {
        if (type === 'banner') {
          this.formData.banner = this.formData.banner.filter((_, i) => i !== index);
          this.$message.success('图片已删除');
        } else if (type === 'video') {
          this.formData.video = this.formData.video.filter((_, i) => i !== index);
          this.$message.success('视频已删除');
        }
        confirmDialog.hide();
      }
    },

    // 获取文件名
    getFileName(url) {
      if (!url) return '未知文件';

      try {
        // 尝试从URL中提取文件名
        const parts = url.split('/');
        let fileName = parts[parts.length - 1];

        // 如果文件名包含查询参数，去除它们
        if (fileName.includes('?')) {
          fileName = fileName.split('?')[0];
        }

        // 如果文件名为空或太短，使用默认名称
        if (!fileName || fileName.length < 3) {
          const isImage = url.toLowerCase().match(/\.(jpg|jpeg|png|gif|webp)$/i);
          const isVideo = url.toLowerCase().match(/\.(mp4|avi|mov|wmv|flv|webm)$/i);

          if (isImage) {
            fileName = '图片文件';
          } else if (isVideo) {
            fileName = '视频文件';
          } else {
            fileName = '未知文件';
          }
        }

        return fileName;
      } catch (error) {
        console.error('解析文件名失败:', error);
        return '未知文件';
      }
    },

    // 预览图片 - 在新标签页中打开
    previewImage(url, index) {
      if (!url) {
        this.$message.warning('图片链接无效');
        return;
      }

      try {
        // 在新标签页中打开图片
        window.open(url, '_blank');
      } catch (error) {
        console.error('打开图片失败:', error);
        this.$message.error('打开图片失败');
      }
    },

    // 播放视频
    playVideo(url) {
      if (!url) {
        this.$message.warning('视频链接无效');
        return;
      }

      try {
        // 在新标签页中打开视频
        window.open(url, '_blank');
      } catch (error) {
        console.error('打开视频失败:', error);
        this.$message.error('打开视频失败');
      }
    },

    // 编辑器创建完成回调
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
  },

  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
};
</script>

<style lang="less" scoped>
.recommend-drawer-body {
  padding: 0;
  height: 100%;
  overflow-y: auto;
}

.recommend-form {
  padding: 20px;

  // 确保表单项纵向布局
  /deep/ .t-form-item {
    display: flex;
    flex-direction: column;
    width: 100%;

    .t-form-item__content {
      display: flex;
      flex-direction: column;
      width: 100%;
    }
  }

  /deep/ .t-upload__dragger {
    width: 100% !important;
    display: flex;
    flex-direction: column;
  }

  // 确保上传组件整体纵向布局
  /deep/ .t-upload {
    display: flex;
    flex-direction: column;
    width: 100%;
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.upload-drag-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #0052d9;
    background-color: #f0f6ff;
  }

  &.uploading {
    background-color: #f0f8ff;
    border-color: #1890ff;
  }

  .upload-text {
    margin-top: 16px;
    text-align: center;
    width: 100%;

    p {
      margin: 0;
      line-height: 1.5;

      &.upload-tips {
        color: #999;
        font-size: 12px;
        margin-top: 4px;
      }
    }
  }
}

// 文件列表头部样式
.file-list-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 8px;
  margin-bottom: 4px;
  width: 100%;

  .file-count {
    font-size: 12px;
    color: #666;
    font-weight: 500;
  }
}

// 文件列表容器 - 纵向布局
.file-list-container {
  border: 1px solid #e7e7e7;
  border-radius: 6px;
  max-height: 200px;
  overflow-y: auto;
  background-color: #fafafa;
  margin-top: 4px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 4px;

  .file-item {
    display: flex;
    align-items: center;
    height: 60px;
    padding: 8px 12px;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.2s;
    position: relative;
    width: 100%;
    box-sizing: border-box;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: #f5f5f5;
    }

    .file-preview {
      width: 44px;
      height: 44px;
      margin-right: 12px;
      border-radius: 4px;
      overflow: hidden;
      cursor: pointer;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f8f8f8;
      border: 1px solid #e0e0e0;
      transition: all 0.2s;

      &:hover {
        border-color: #1890ff;
        box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
      }

      .preview-thumbnail {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 3px;
      }

      .video-thumbnail {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #666;
        position: relative;

        .play-icon {
          position: absolute;
          bottom: 2px;
          right: 2px;
          font-size: 10px;
          color: #1890ff;
        }
      }
    }

    .file-info {
      flex: 1;
      display: flex;
      align-items: center;
      min-width: 0;

      .file-icon {
        margin-right: 8px;
        color: #1890ff;
        flex-shrink: 0;
        font-size: 16px;
      }

      .file-name {
        font-size: 14px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        line-height: 1.4;
      }
    }

    .file-actions {
      display: flex;
      align-items: center;
      gap: 4px;
      flex-shrink: 0;

      .t-button {
        opacity: 0.7;
        transition: opacity 0.2s;

        &:hover {
          opacity: 1;
        }
      }
    }
  }

  // 当列表为空时的样式
  &:empty {
    display: none;
  }
}

.rich-editor-wrapper {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;

  :deep(.w-e-toolbar) {
    border-bottom: 1px solid #d9d9d9;
  }

  :deep(.w-e-text-container) {
    min-height: 400px !important;
    max-height: 500px !important;
    overflow-y: auto;
  }

  :deep(.w-e-text-placeholder) {
    top: 10px;
    left: 10px;
  }
}
</style>
